package com.questionnaire.interceptor;

import com.questionnaire.pojo.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor  implements HandlerInterceptor{
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {

        String url = httpServletRequest.getRequestURI();

        //login页面直接访问不需要登录
        if(url.indexOf("/login") >= 0) return true;

        HttpSession session = httpServletRequest.getSession();
        User loginUser = (User) session.getAttribute("loginUser");

        if(loginUser == null) return true;

        //尚未登录 跳转到登录页
        httpServletRequest.setAttribute("msg", "尚未登录,请先登录系统!");
        httpServletRequest.getRequestDispatcher("/views/login.jsp").forward(httpServletRequest, httpServletResponse);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
